package com.wxmit.module.system.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.wxmit.module.system.domain.SysUser;
import com.wxmit.system.base.domain.PageDTO;
import org.springframework.stereotype.Service;
import com.wxmit.system.base.core.ShushanServiceImpl;
import com.wxmit.module.system.mapper.ConfigMapper;
import com.wxmit.module.system.domain.SysConfig;
import com.wxmit.module.system.service.IConfigService;

import java.util.Objects;

/**
 * configService业务层处理
 *
 * @author huangxiong
 * @date   2024-4-16
 */
@Service
public class ConfigServiceImpl extends ShushanServiceImpl<ConfigMapper, SysConfig> implements IConfigService {

    @Override
    protected void processPageDTO(PageDTO<SysConfig> pageDTO, LambdaQueryChainWrapper<SysConfig> lambdaQuery) {
        SysConfig searchData = pageDTO.getSearchData();
        lambdaQuery.eq(StrUtil.isNotEmpty(searchData.getConfigGroup()),SysConfig::getConfigGroup, searchData.getConfigGroup());
        lambdaQuery.likeRight(StrUtil.isNotEmpty(searchData.getName()),SysConfig::getName, searchData.getName());
        lambdaQuery.eq(StrUtil.isNotEmpty(searchData.getType()),SysConfig::getType, searchData.getType());
    }

    @Override
    public boolean save(SysConfig entity) {
        if(StrUtil.isEmpty(entity.getConfigGroup())){
            entity.setConfigGroup("默认分组");
        }
        checkNameUnion(entity.getName(),null);
        return super.save(entity);
    }

    @Override
    public boolean updateById(SysConfig entity) {
        checkNameUnion(entity.getName(),entity.getId());
        return super.updateById(entity);
    }


    private void checkNameUnion(String name,Long id){
        LambdaQueryChainWrapper<SysConfig> lambdaQuery = lambdaQuery();
        lambdaQuery.eq(SysConfig::getName,name);
        if(Objects.nonNull(id)){
            lambdaQuery.ne(SysConfig::getId,id);
        }
        Long count = lambdaQuery.count();
        Assert.isTrue(count.compareTo(0L) == 0,"当前配置名已被占用！");
    }
}
